package cn.gong.movie.ui;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.gong.movie.bean.Drama;
import cn.gong.movie.data.DataDrama;
import cn.gong.movie.enums.DbTaskType;
import cn.gong.movie.utils.DateUtils1;
import framework.annotation.ClickMethod;
import framework.annotation.InjectView;
import framework.base.BaseAct;
import framework.config.Strings;
import framework.view.wheel.ArrayWheelAdapter;
import framework.view.wheel.OnWheelChangedListener;
import framework.view.wheel.WheelView;

public class ActSeenDramaInfoEdit extends BaseAct {

	@InjectView(R.id.title_bar_tv_title)
	private TextView titleTv;
	@InjectView(R.id.add_drama_et_name)
	protected EditText nameEt;
	@InjectView(R.id.add_drama_et_episode)
	protected EditText episodeEt;

	@InjectView(R.id.add_drama_wv_year)
	private WheelView yearWv;
	@InjectView(R.id.add_drama_wv_month)
	private WheelView monthWv;
	@InjectView(R.id.add_drama_wv_day)
	private WheelView dayWv;

	@InjectView(R.id.add_drama_tv_date)
	protected TextView dateTv;

	@InjectView(R.id.add_drama_ll_wheel_date)
	private LinearLayout dateWheelLl;
	private Drama drama;
	private String dateOri;

	@Override
	public void onCreateAct(Bundle savedInstanceState) {
		super.onCreateAct(savedInstanceState);
		setContentView(R.layout.add_drama);

		drama = (Drama) getIntent().getSerializableExtra(Strings.INTENT_EXTRA_DRAMA);

		setText(titleTv, "编辑电视剧");
		viewGone(R.id.title_bar_ib_left);

		setText(nameEt, drama.getName());

		setText(episodeEt, drama.getTotalNum());

		dateOri = DateUtils1.format("yyyyMMdd", "yyyy-MM-dd", drama.getDate());

		setText(dateTv, dateOri + "(原:" + dateOri + ")");

		nameEt.setOnFocusChangeListener(cl);
		episodeEt.setOnFocusChangeListener(cl);

	}

	private OnFocusChangeListener cl = new OnFocusChangeListener() {

		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			if (hasFocus) {
				viewGone(R.id.add_drama_ll_wheel_date);
			}
		}
	};

	@ClickMethod(R.id.add_drama_et_name)
	protected void clickName(View view) {
		viewGone(R.id.add_drama_ll_wheel_date);
	}

	@ClickMethod(R.id.add_drama_et_episode)
	protected void clickEpisode(View view) {
		viewGone(R.id.add_drama_ll_wheel_date);
	}

	private boolean isInitDate;
	private ArrayList<String> yearArray;
	private ArrayList<String> monthArray;

	@ClickMethod(R.id.add_drama_ll_data)
	protected void clickData(View view) {
		inputHidden(nameEt);
		inputHidden(episodeEt);
		viewShow(R.id.add_drama_ll_wheel_date);

		if (!isInitDate) {
			isInitDate = !isInitDate;
			yearArray = DateUtils1.getYearArrayTotal();
			monthArray = DateUtils1.getMonthArrayTotal();
			initWheelDate();
		}
	}

	private void setDateTv() {
		setText(dateTv, getYmd() + "(原:" + dateOri + ")");
	}

	private String getYmd() {
		return getWvItem(yearWv) + "-" + getWvItem(monthWv) + "-" + getWvItem(dayWv);
	}

	private String getWvItem(WheelView wv) {
		try {
			return wv.getAdapter().getItem(wv.getCurrentItem());
		} catch (Exception e) {
			return "";
		}
	}

	private String getYmdInt() {
		return getWvItem(yearWv) + getWvItem(monthWv) + getWvItem(dayWv);
	}

	private void initWheelDate() {
		yearWv.setAdapter(new ArrayWheelAdapter<String>(yearArray));
		yearWv.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				int currentItem = monthWv.getCurrentItem();
				if (currentItem == 1) {
					int itemsCount = dayWv.getAdapter().getItemsCount();
					log("itemsCount:" + itemsCount);
					ArrayList<String> dayArray = DateUtils1.getDayArrayTotal(yearArray.get(yearWv.getCurrentItem()), currentItem);
					if (dayArray.size() != itemsCount) {
						dayWv.setAdapter(new ArrayWheelAdapter<String>(dayArray));
						dayWv.setCurrentItem(dayArray.size() / 2);
					}
				}
				setDateTv();

			}
		});

		monthWv.setAdapter(new ArrayWheelAdapter<String>(monthArray));
		monthWv.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				int itemsCount = dayWv.getAdapter().getItemsCount();
				int currentItem = dayWv.getCurrentItem();
				ArrayList<String> dayArray = DateUtils1.getDayArrayTotal(yearArray.get(yearWv.getCurrentItem()), newValue);
				if (dayArray.size() != itemsCount) {
					dayWv.setAdapter(new ArrayWheelAdapter<String>(dayArray));
					if (currentItem < dayArray.size()) {
						dayWv.setCurrentItem(currentItem);
					} else {
						dayWv.setCurrentItem(dayArray.size() / 2);
					}
				}
				setDateTv();

			}
		});
		dayWv.setAdapter(new ArrayWheelAdapter<String>(DateUtils1.getDayArrayTotal("", 0)));
		dayWv.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// setText(dateTv, getYmd() + "(原:" + startStr + ")");
				setDateTv();
			}
		});

		yearWv.setCurrentItem(99);

		monthWv.setCurrentItem(6);

		dayWv.setCurrentItem(0);

	}

	@ClickMethod(R.id.add_drama_ib_delete_name)
	protected void clickDeleteName(View view) {
		setText(nameEt, "");
	}

	@ClickMethod(R.id.add_drama_ib_delete_episode)
	protected void clickDeleteEpisode(View view) {
		setText(episodeEt, "");
	}

	@ClickMethod(R.id.title_bar_ib_right)
	protected void clickClose(View view) {
		closeAct();
		animTranslateTopIn();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (dateWheelLl.getVisibility() == View.VISIBLE) {
				viewGone(dateWheelLl);
			} else {
				clickClose(null);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@ClickMethod(R.id.add_drama_ll_add)
	protected void clickAdd(View view) {

		String name = nameEt.getText().toString();
		if (TextUtils.isEmpty(name)) {
			toast("请添加名字");
			return;
		}

		String episode = episodeEt.getText().toString();
		if (TextUtils.isEmpty(episode)) {
			toast("请添加集数");
			return;
		}

		Integer episodeNum = null;

		try {
			episodeNum = new Integer(episode);

			if (episodeNum > 500) {
				toast("集数请不要超过500");
				return;
			}

		} catch (Exception e) {
			toast("集数请不要超过500");
			return;
		}

		String ymd = getYmdInt();
		if (!TextUtils.isEmpty(ymd)) {
			drama.setDate(ymd);
		}

		drama.setName(name);
		if (episodeNum != drama.getTotalNum()) {
			boolean[] newEpisodes = new boolean[episodeNum];

			boolean[] episodes = drama.getEpisodes();

			int totalNum = episodeNum > drama.getTotalNum() ? drama.getTotalNum() : episodeNum;

			int seenNum = 0;

			for (int i = 0; i < totalNum; i++) {
				boolean seen = episodes[i];
				if (seen) {
					seenNum++;
				}
				newEpisodes[i] = seen;
			}

			drama.setEpisodes(newEpisodes);
			drama.setSeenNum(seenNum);
		}
		drama.setTotalNum(episodeNum);
		drama.setWatchTime(System.currentTimeMillis());

		if (drama.isSeen()) {
			drama.setStatus(2);
		} else {
			drama.setStatus(0);
		}

		log(drama);

		DataDrama.updateDrama(getContext(), drama, getDBCallBack());

	}

	@Override
	public void onDbCallBack(int dbTaskType, Object data) {
		super.onDbCallBack(dbTaskType, data);
		switch (DbTaskType.values()[dbTaskType]) {
		case dbTsUpdateDrama:
			dbTsUpdateDrama(data);
			break;
		}
	}

	private void dbTsUpdateDrama(Object data) {
		Intent intent = new Intent();
		intent.putExtra(Strings.INTENT_EXTRA_DRAMA, (Drama) data);
		closeActForResultOk(intent);
	}
}
